package com.training.controller;

import com.training.entity.User;
import com.training.entity.Class;
import com.training.entity.Student;
import com.training.entity.Course;
// ... (其他 import 保持不变)
import com.training.service.ClassService;
import com.training.service.TeacherService;
import com.training.service.StudentService;
import com.training.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam; // 确保导入这个
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/class") // All requests in this controller will start with /class
public class ClassController {

    @Autowired
    private ClassService classService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private CourseService courseService;

    /**
     * Display the class management page for teachers, with search functionality.
     * --- MODIFIED ---
     * @param keyword Search keyword for class name (optional)
     * @param session HttpSession object
     * @param model Model object
     * @return Template name for the class management page
     */
    @GetMapping("/manage")
    public String manageClasses(@RequestParam(value = "keyword", required = false) String keyword, // --- MODIFIED: 1. 添加 @RequestParam 来接收关键词 ---
                                HttpSession session, Model model) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }

        // --- MODIFIED: 2. 调用 service 方法时传入关键词 ---
        List<Class> classes = classService.getAllClasses(keyword);

        model.addAttribute("classes", classes);
        model.addAttribute("loggedInUser", loggedInUser);

        // --- NEW: 3. 将关键词传回前端，用于在搜索框中显示 ---
        model.addAttribute("keyword", keyword);

        return "class-manage";
    }

    // ... 其他所有方法 (@GetMapping("/create"), @PostMapping("/create"), etc.) 都保持原样，无需改动 ...

    /**
     * Display the form for creating a new class.
     * @param model Model object
     * @param session HttpSession object
     * @return Template name for the class creation form
     */
    @GetMapping("/create")
    public String showCreateClassForm(Model model, HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }
        model.addAttribute("classObj", new Class());
        model.addAttribute("loggedInUser", loggedInUser);
        return "class-create-edit";
    }

    /**
     * Handle the submission of the class creation form.
     * @param classObj Class object from the form
     * @param session HttpSession object
     * @param redirectAttributes RedirectAttributes object to pass messages
     * @return Redirect to class management page
     */
    @PostMapping("/create")
    public String createClass(@ModelAttribute Class classObj, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }

        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        if (teacherId == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "无法获取教师ID，请联系管理员。");
            return "redirect:/class/manage";
        }
        classObj.setTeaId(teacherId);

        try {
            boolean success = classService.saveClass(classObj);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "班级创建成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "班级创建失败，请稍后再试。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "班级创建失败：" + e.getMessage());
        }
        return "redirect:/class/manage";
    }

    /**
     * Display the form for editing an existing class.
     * @param id Class ID to edit
     * @param model Model object
     * @param session HttpSession object
     * @param redirectAttributes RedirectAttributes object
     * @return Template name for the class edit form
     */
    @GetMapping("/edit/{id}")
    public String showEditClassForm(@PathVariable("id") Long id, Model model, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }

        Class classObj = classService.getClassById(id);
        if (classObj == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "班级不存在或已被删除。");
            return "redirect:/class/manage";
        }
        model.addAttribute("classObj", classObj);
        model.addAttribute("loggedInUser", loggedInUser);
        return "class-create-edit";
    }

    /**
     * Handle the submission of the class edit form.
     * @param classObj Class object from the form
     * @param redirectAttributes RedirectAttributes object
     * @param session HttpSession object
     * @return Redirect to class management page
     */
    @PostMapping("/edit")
    public String editClass(@ModelAttribute Class classObj, RedirectAttributes redirectAttributes, HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }

        Class existingClass = classService.getClassById(classObj.getId());
        if (existingClass != null) {
            classObj.setTeaId(existingClass.getTeaId());
            classObj.setClassStuNum(existingClass.getClassStuNum());
            classObj.setClassCouNum(existingClass.getClassCouNum());
        } else {
            redirectAttributes.addFlashAttribute("errorMessage", "要编辑的班级不存在。");
            return "redirect:/class/manage";
        }

        try {
            boolean success = classService.saveClass(classObj);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "班级更新成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "班级更新失败，请稍后再试。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "班级更新失败：" + e.getMessage());
        }
        return "redirect:/class/manage";
    }

    /**
     * Handle the deletion of a class.
     * @param id Class ID to delete
     * @param redirectAttributes RedirectAttributes object
     * @param session HttpSession object
     * @return Redirect to class management page
     */
    @PostMapping("/delete/{id}")
    public String deleteClass(@PathVariable("id") Long id, RedirectAttributes redirectAttributes, HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }

        try {
            boolean success = classService.deleteClass(id);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "班级删除成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "班级删除失败，请稍后再试。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "班级删除失败：" + e.getMessage());
        }
        return "redirect:/class/manage";
    }

    /**
     * Display the student management page for a specific class.
     * @param classId Class ID
     * @param model Model object
     * @param session HttpSession object
     * @param redirectAttributes RedirectAttributes object
     * @return Template name for the class student management page
     */
    @GetMapping("/{classId}/students/manage")
    public String manageClassStudents(@PathVariable("classId") Long classId, Model model, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !("TEACHER".equalsIgnoreCase(loggedInUser.getRole()) || "STUDENT".equalsIgnoreCase(loggedInUser.getRole()))) {
            return "redirect:/login";
        }

        Class classObj = classService.getClassById(classId);
        if (classObj == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "班级不存在或已被删除。");
            return "redirect:/class/manage";
        }

        if ("STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            Student student = studentService.getStudentByUserId(loggedInUser.getId());
            if (student == null) {
                session.invalidate();
                redirectAttributes.addFlashAttribute("error", "学生信息不完整，请联系管理员。");
                return "redirect:/login";
            }
            if (!classService.isStudentEnrolledInClass(classId, student.getId())) {
                redirectAttributes.addFlashAttribute("errorMessage", "您无权查看该班级的学生列表。");
                return "redirect:/student/dashboard";
            }
        }

        List<Student> studentsInClass = classService.getStudentsByClassId(classId);

        model.addAttribute("classObj", classObj);
        model.addAttribute("studentsInClass", studentsInClass);
        model.addAttribute("loggedInUser", loggedInUser);
        return "class-students-manage";
    }

    /**
     * Handle adding a student to a class.
     * @param classId Class ID
     * @param studentNum Student number to add
     * @param redirectAttributes RedirectAttributes object
     * @param session HttpSession object
     * @return Redirect back to class student management page
     */
    @PostMapping("/{classId}/students/add")
    public String addStudentToClass(@PathVariable("classId") Long classId,
                                    @RequestParam("studentNum") String studentNum,
                                    HttpSession session,
                                    RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }

        try {
            Student studentToAdd = studentService.getStudentByStuNum(studentNum);
            if (studentToAdd == null) {
                redirectAttributes.addFlashAttribute("errorMessage", "学号为 " + studentNum + " 的学生不存在。");
                return "redirect:/class/" + classId + "/students/manage";
            }

            boolean success = classService.addStudentToClass(classId, studentToAdd.getId());
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "学生 " + studentToAdd.getStuName() + " (学号: " + studentNum + ") 添加成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "学生 " + studentToAdd.getStuName() + " (学号: " + studentNum + ") 已在该班级中或添加失败，请稍后再试。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "添加学生失败：" + e.getMessage());
        }
        return "redirect:/class/" + classId + "/students/manage";
    }

    /**
     * Handle removing a student from a class.
     * @param classId Class ID
     * @param studentId Student ID to remove
     * @param redirectAttributes RedirectAttributes object
     * @param session HttpSession object
     * @return Redirect back to class student management page
     */
    @PostMapping("/{classId}/students/delete/{studentId}")
    public String removeStudentFromClass(@PathVariable("classId") Long classId,
                                         @PathVariable("studentId") Long studentId,
                                         HttpSession session,
                                         RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }

        try {
            boolean success = classService.removeStudentFromClass(classId, studentId);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "学生移除成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "学生移除失败，请稍后再试。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "移除学生失败：" + e.getMessage());
        }
        return "redirect:/class/" + classId + "/students/manage";
    }

    /**
     * Display the course management page for a specific class.
     * @param classId Class ID
     * @param model Model object
     * @param session HttpSession object
     * @param redirectAttributes RedirectAttributes object
     * @return Template name for the class course management page
     */
    @GetMapping("/{classId}/courses/manage") // Respond to GET requests for /class/{classId}/courses/manage
    public String manageClassCourses(@PathVariable("classId") Long classId, Model model, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !("TEACHER".equalsIgnoreCase(loggedInUser.getRole()) || "STUDENT".equalsIgnoreCase(loggedInUser.getRole()))) {
            return "redirect:/login";
        }

        Class classObj = classService.getClassById(classId);
        if (classObj == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "班级不存在或已被删除。");
            return "redirect:/class/manage";
        }

        if ("STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            Student student = studentService.getStudentByUserId(loggedInUser.getId());
            if (student == null) {
                session.invalidate();
                redirectAttributes.addFlashAttribute("error", "学生信息不完整，请联系管理员。");
                return "redirect:/login";
            }
            if (!classService.isStudentEnrolledInClass(classId, student.getId())) {
                redirectAttributes.addFlashAttribute("errorMessage", "您无权查看该班级的课程。");
                return "redirect:/student/dashboard";
            }
        }

        List<Course> classCourses = classService.getCoursesByClassId(classId);
        List<Course> allAvailableCourses = courseService.getAllCourses();

        // Filter out courses already in the class from the available courses list
        List<Course> coursesToAdd = allAvailableCourses.stream()
                .filter(availableCourse -> classCourses.stream()
                        .noneMatch(classCourse -> classCourse.getId().equals(availableCourse.getId())))
                .collect(Collectors.toList());

        model.addAttribute("classObj", classObj);
        model.addAttribute("classCourses", classCourses);
        model.addAttribute("coursesToAdd", coursesToAdd);
        model.addAttribute("loggedInUser", loggedInUser);
        return "class-courses-manage";
    }

    /**
     * Handle adding a course to a class.
     * IMPORTANT: The previous CourseController also had this method.
     * This method is moved here to ClassController and its mapping adjusted
     * to match the frontend form submission from class-courses-manage.html
     * and add-course-to-class.html for consistency and proper routing.
     *
     * @param classId Class ID
     * @param couId Course ID to add
     * @param redirectAttributes RedirectAttributes object
     * @param session HttpSession object
     * @return Redirect back to class course management page
     */
    // Modified: Changed URL path to /class/{classId}/add-course-to-class
    // This is the correct endpoint for the form in class-courses-manage.html
    // and also the new unified endpoint for add-course-to-class.html
    @PostMapping("/{classId}/add-course-to-class") // <--- 修改此处，匹配前端期望的 URL
    public String addCourseToClass(@PathVariable("classId") Long classId,
                                   @RequestParam("courseId") Long couId, // <--- 修改此处，确保参数名与前端表单的 input name 匹配
                                   HttpSession session,
                                   RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }

        try {
            boolean success = classService.addCourseToClass(classId, couId);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "课程添加成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "课程已在该班级中或添加失败，请稍后再试。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "添加课程失败：" + e.getMessage());
        }
        return "redirect:/class/" + classId + "/courses/manage";
    }

    /**
     * Handle removing a course from a class.
     * @param classId Class ID
     * @param courseId Course ID to remove
     * @param redirectAttributes Used to pass messages after redirection
     * @return Redirect to the class courses management page
     */
    @PostMapping("/{classId}/courses/delete/{courseId}")
    public String removeCourseFromClass(@PathVariable("classId") Long classId,
                                        @PathVariable("courseId") Long courseId,
                                        HttpSession session,
                                        RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) {
            return "redirect:/login";
        }

        try {
            boolean success = classService.removeCourseFromClass(classId, courseId);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "课程删除成功！");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "课程删除失败，请稍后再试。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("errorMessage", "删除课程失败：" + e.getMessage());
        }

        return "redirect:/class/" + classId + "/courses/manage";
    }
}